using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Win32;
using System.Text;

namespace LicenseApp.Client
{
    /// <summary>
    /// 强化的授权文件存储 - 多重存储协防机制
    /// </summary>
    public static class RobustLicenseStorage
    {
        // 注册表存储（使用自定义后缀，确保不与系统设置冲突）
        private const string REGISTRY_KEY = @"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced";
        private const string REGISTRY_VALUE = "TaskbarGlomLevel_ZhyLsHK"; // 自定义后缀，确保唯一

        // 🎯 简化为两种协防：应用目录文件 + 注册表
        private static readonly string[] _licenseStoragePaths = new[]
        {
            // 程序目录（主要存储位置）
            GetProgramDirectoryLicensePath(),

            // 程序目录备份（协防位置）
            GetProgramDirectoryBackupPath()
        };

        /// <summary>
        /// 获取程序目录的授权文件路径
        /// </summary>
        private static string GetProgramDirectoryLicensePath()
        {
            string assemblyFilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName ?? "";
            string assemblyDirPath = System.IO.Path.GetDirectoryName(assemblyFilePath) ?? "";
            return System.IO.Path.Combine(assemblyDirPath, "System.ZhyLsHK.dll");
        }

        /// <summary>
        /// 获取程序目录的备份授权文件路径
        /// </summary>
        private static string GetProgramDirectoryBackupPath()
        {
            string assemblyFilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName ?? "";
            string assemblyDirPath = System.IO.Path.GetDirectoryName(assemblyFilePath) ?? "";
            return System.IO.Path.Combine(assemblyDirPath, ".license_backup.tmp");
        }

        /// <summary>
        /// 从所有存储位置加载授权码（文件 + 注册表协防检查）
        /// </summary>
        public static string? LoadLicenseCode()
        {
            var licenseCodes = new List<string>();

            Console.WriteLine("[RobustLicenseStorage] 开始从多个位置加载授权码...");

            // 1. 从文件存储加载
            foreach (var path in _licenseStoragePaths)
            {
                try
                {
                    if (File.Exists(path))
                    {
                        var content = File.ReadAllText(path)?.Trim();
                        if (!string.IsNullOrEmpty(content))
                        {
                            licenseCodes.Add(content);
                            Console.WriteLine($"[RobustLicenseStorage] 从文件加载授权码: {path}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[RobustLicenseStorage] 从文件加载失败 {path}: {ex.Message}");
                }
            }

            // 2. 从注册表加载
            try
            {
                var registryLicense = LoadFromRegistry();
                if (!string.IsNullOrEmpty(registryLicense))
                {
                    licenseCodes.Add(registryLicense);
                    Console.WriteLine("[RobustLicenseStorage] 从注册表加载授权码");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[RobustLicenseStorage] 从注册表加载失败: {ex.Message}");
            }
            
            if (!licenseCodes.Any())
            {
                Console.WriteLine("[RobustLicenseStorage] 未找到任何授权文件");
                return null;
            }
            
            // 选择最常见的授权码（防止部分文件被篡改）
            var mostCommon = licenseCodes
                .GroupBy(x => x)
                .OrderByDescending(g => g.Count())
                .First()
                .Key;
                
            Console.WriteLine($"[RobustLicenseStorage] 找到 {licenseCodes.Count} 个授权文件，选择最常见的授权码");
            return mostCommon;
        }

        /// <summary>
        /// 保存授权码到所有存储位置（协防保存）
        /// </summary>
        public static bool SaveLicenseCode(string licenseCode)
        {
            if (string.IsNullOrEmpty(licenseCode))
                return false;
                
            Console.WriteLine("[RobustLicenseStorage] 开始保存授权码到多个位置...");
            
            int successCount = 0;
            
            foreach (var path in _licenseStoragePaths)
            {
                try
                {
                    // 🛠️ 修复：增强的目录创建和权限检查
                    var directory = Path.GetDirectoryName(path);
                    if (!string.IsNullOrEmpty(directory))
                    {
                        if (!Directory.Exists(directory))
                        {
                            try
                            {
                                Directory.CreateDirectory(directory);
                                Console.WriteLine($"[RobustLicenseStorage] 创建目录: {directory}");
                            }
                            catch (UnauthorizedAccessException)
                            {
                                Console.WriteLine($"[RobustLicenseStorage] 目录创建权限不足，跳过: {directory}");
                                continue; // 跳过这个路径，尝试下一个
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine($"[RobustLicenseStorage] 目录创建失败，跳过: {directory} - {ex.Message}");
                                continue; // 跳过这个路径，尝试下一个
                            }
                        }
                    }

                    // 🛠️ 修复：检查文件写入权限
                    try
                    {
                        // 保存授权码
                        File.WriteAllText(path, licenseCode);
                        Console.WriteLine($"[RobustLicenseStorage] 成功保存到: {path}");
                    }
                    catch (UnauthorizedAccessException)
                    {
                        Console.WriteLine($"[RobustLicenseStorage] 文件写入权限不足，跳过: {path}");
                        continue; // 跳过这个路径，尝试下一个
                    }

                    // 设置隐藏属性（可选，失败不影响功能）
                    try
                    {
                        // 如果是用户主目录的隐藏文件夹，设置文件夹为隐藏
                        if (path.Contains(".CcdqLicenseApp"))
                        {
                            var hiddenDirectory = Path.GetDirectoryName(path);
                            if (!string.IsNullOrEmpty(hiddenDirectory) && Directory.Exists(hiddenDirectory))
                            {
                                var dirInfo = new DirectoryInfo(hiddenDirectory);
                                dirInfo.Attributes |= FileAttributes.Hidden;
                            }
                        }

                        // 设置文件为隐藏
                        File.SetAttributes(path, FileAttributes.Hidden);
                    }
                    catch
                    {
                        // 设置属性失败不影响功能
                    }

                    successCount++;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[RobustLicenseStorage] 保存失败 {path}: {ex.Message}");
                }
            }

            // 保存到注册表
            try
            {
                SaveToRegistry(licenseCode);
                successCount++;
                Console.WriteLine("[RobustLicenseStorage] 成功保存到注册表");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[RobustLicenseStorage] 保存到注册表失败: {ex.Message}");
            }

            Console.WriteLine($"[RobustLicenseStorage] 保存完成，成功 {successCount}/{_licenseStoragePaths.Length + 1} 个位置");
            return successCount > 0;
        }

        /// <summary>
        /// 检查是否存在授权文件（任意位置）
        /// </summary>
        public static bool HasLicenseFile()
        {
            return _licenseStoragePaths.Any(path => File.Exists(path));
        }

        /// <summary>
        /// 清除所有位置的授权文件
        /// </summary>
        public static bool ClearAllLicenseFiles()
        {
            Console.WriteLine("[RobustLicenseStorage] 开始清除所有位置的授权文件...");
            
            int deletedCount = 0;
            
            foreach (var path in _licenseStoragePaths)
            {
                try
                {
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                        deletedCount++;
                        Console.WriteLine($"[RobustLicenseStorage] 删除成功: {path}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[RobustLicenseStorage] 删除失败 {path}: {ex.Message}");
                }
            }
            
            Console.WriteLine($"[RobustLicenseStorage] 清除完成，删除 {deletedCount} 个文件");
            return deletedCount > 0;
        }

        /// <summary>
        /// 获取授权文件存储统计信息
        /// </summary>
        public static string GetStorageStatistics()
        {
            var existingFiles = new List<string>();
            var fileContents = new Dictionary<string, string>();
            
            foreach (var path in _licenseStoragePaths)
            {
                try
                {
                    if (File.Exists(path))
                    {
                        existingFiles.Add(path);
                        var content = File.ReadAllText(path)?.Trim();
                        if (!string.IsNullOrEmpty(content))
                        {
                            var shortContent = content.Length > 50 ? content.Substring(0, 50) + "..." : content;
                            fileContents[path] = shortContent;
                        }
                    }
                }
                catch (Exception ex)
                {
                    fileContents[path] = $"读取失败: {ex.Message}";
                }
            }
            
            var result = $"=== 授权文件存储统计 ===\n";
            result += $"总存储位置: {_licenseStoragePaths.Length}\n";
            result += $"存在文件: {existingFiles.Count}\n\n";
            
            for (int i = 0; i < _licenseStoragePaths.Length; i++)
            {
                var path = _licenseStoragePaths[i];
                var exists = File.Exists(path);
                var status = exists ? "✅ 存在" : "❌ 不存在";
                
                result += $"{i + 1}. {status} - {path}\n";
                
                if (fileContents.ContainsKey(path))
                {
                    result += $"   内容: {fileContents[path]}\n";
                }
                
                result += "\n";
            }
            
            return result;
        }

        /// <summary>
        /// 获取所有存储位置路径（用于调试）
        /// </summary>
        public static string[] GetAllStoragePaths()
        {
            return _licenseStoragePaths.ToArray();
        }

        /// <summary>
        /// 从注册表加载授权码
        /// </summary>
        private static string? LoadFromRegistry()
        {
            try
            {
                var value = Registry.GetValue(REGISTRY_KEY, REGISTRY_VALUE, null);
                if (value is string strValue && !string.IsNullOrEmpty(strValue))
                {
                    // 简单解码（Base64）
                    var bytes = Convert.FromBase64String(strValue);
                    return Encoding.UTF8.GetString(bytes);
                }
                return null;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 保存授权码到注册表
        /// </summary>
        private static void SaveToRegistry(string licenseCode)
        {
            try
            {
                // 简单编码（Base64）
                var bytes = Encoding.UTF8.GetBytes(licenseCode);
                var encodedValue = Convert.ToBase64String(bytes);
                Registry.SetValue(REGISTRY_KEY, REGISTRY_VALUE, encodedValue, RegistryValueKind.String);
            }
            catch
            {
                throw; // 重新抛出异常，让调用者处理
            }
        }
    }
}
